import {
    getOrderConfig,
    orderConfirm,
    getCouponsOrderPrice,
    orderCreate,
    postOrderComputed
} from '../../api/order.js';

import {
    openPaySubscribe
} from '../../utils/SubscribeMessage.js';
import {
    baseConfig,
    getAgreement,
} from '../../api/api.js';
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        textareaStatus: true,
        parameter: {
            'navbar': '1',
            'return': '1',
            'title': '确认订单',
        },
        showInput: false,
        policy: {
            isShow: false,
            isAgree: false,
            content: '',
        },
        //支付方式
        cartArr: [{
                "name": "微信支付",
                "icon": "icon-weixin2",
                value: 'weixin',
                title: '微信快捷支付'
            },
            {
                "name": "余额支付",
                "icon": "icon-icon-test",
                value: 'yue',
                title: '可用余额:'
            },
            {
                "name": "线下支付",
                "icon": "icon-yinhangqia",
                value: 'offline',
                title: '线下支付'
            },
        ],
        payType: 'weixin', //支付方式
        openType: 1, //优惠券打开方式 1=使用
        active: 0, //支付方式切换
        coupon: {
            coupon: false,
            list: [],
            statusTile: '立即使用'
        }, //优惠券组件
        address: {
            address: false
        }, //地址组件

        pinkId: 0, //拼团id
        addressId: 0, //地址id
        couponId: 0, //优惠券id
        cartId: '', //购物车id
        userInfo: {}, //用户信息

        couponTitle: '请选择', //优惠券
        coupon_price: 0, //优惠券抵扣金额
        useIntegral: false, //是否使用积分
        integral_price: 0, //积分抵扣金额
        ChangePrice: 0, //使用积分抵扣变动后的金额
        formIds: [], //收集formid
        status: 0,
        is_address: false,
        isClose: false,
        toPay: false, //修复进入支付时页面隐藏从新刷新页面
        shippingType: 0,
        system_store: {},
        storePostage: 0,
        contacts: '',
        contactsTel: '',
        mydata: {},
        addressInfo: {}, //地址信息
        caniste_price: "10", //海报筒单价
        poster_price: '0', //海报筒总价
        address: [], //地址信息
        needAddress: 0, //需要的身份信息
        haiguanDes: "", //海关描述
        selfCount: 1, //每人限制数量
        order_information_limit: 1, // 每个地址购买数量上限
        real_name: '',
        birthday: '',
        qq: '',
        wechat: '',
        sign: '',
        mark: '', //备注信息
        packNum: 0, //海报筒数量
        maxPackNum: 0, //最大海报同数量
        order_config: {},
        totalAmount: 0,
    },
    /**
     * 授权回调事件
     * 
     */
    onLoadFun: function() {
        this.getBaseConfig();
        this.getConfirm();
        this.getAgreement();

    },
    /**
     * 获取协议
     * @param boolean 是否展示购物车动画和重置属性
     */
    getAgreement: function() {
        var that = this;
        getAgreement().then(res => {
            //html转wxml
            this.setData({
                'policy.content': res.data.info.payment_agree
            })
            console.log('this.data.policy---->', this.data.policy);
        }).catch(err => {
            console.log('err---->', err);
        })
    },
    _onShowPolicy: function(e) {
        this.setData({
            'policy.isShow': true,
        })
    },
    _onClosePolicy: function(e) {
        this.setData({
            'policy.isShow': false,
        });
        console.log('this.data.policy---->', this.data.policy);
    },
    _onAgreementPolicy: function(e) {
        console.log('e---->', e);
        this.setData({
            'policy.isShow': false,
            'policy.isAgree': true,
        });
    },
    _onChangeAgreement: function(e) {
        console.log('e---->', e);
        this.setData({
            'policy.isAgree': !this.data.policy.isAgree
        })
    },
    /**
     * 修改海报同数量
     * @param {} e 
     */
    changePackNum(e) {
        let that = this
        let poster_price = that.data.caniste_price;
        switch (e.currentTarget.dataset.key) {
            case "-":
                let jian = 0
                if (that.data.packNum > 0) {
                    jian = --that.data.packNum
                }
                poster_price = poster_price * jian
                that.setData({
                    packNum: jian,
                    poster_price: poster_price,
                }, () => this._calculateTotalAmount());
                break
            case "+":
                let jia = that.data.maxPackNum
                if (that.data.packNum < that.data.maxPackNum) {
                    jia = ++that.data.packNum
                }
                poster_price = poster_price * jia
                that.setData({
                    packNum: jia,
                    poster_price: poster_price,
                }, () => this._calculateTotalAmount());
                break
        }

    },
    getBaseConfig() {
        let that = this
        baseConfig().then(res => {
            let needAddress = 1
            if (that.data.allNum && res.data.max_pay_count) {
                // needAddress = Math.ceil(that.data.allNum / res.data.max_pay_count)
                needAddress = Math.ceil(that.data.allNum / res.data.order_information_limit)
            }
            that.setData({
                haiguanDes: res.data.buy_information || "",
                selfCount: res.data.max_pay_count || 1,
                order_information_limit: res.data.order_information_limit || 1,
                needAddress: needAddress,
                order_config: res.data,
            })
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

        this.setData({
            textareaStatus: true
        });

        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1]; //当前页面
        if (currPage.data.storeItem) {
            let json = currPage.data.storeItem;
            this.setData({
                system_store: json,
            });
        }
    },

    getOrderConfig() {
        getOrderConfig()
            .then(res => {
                console.log('res---->', res);
                this.order_config = res.data;
            })
            .catch(() => {});
    },
    computedPrice: function() {
        let shippingType = this.data.shippingType;
        let dataText = [];
        if (this.data.address.length > 0) {
            for (var i in this.data.address) {
                dataText.push(this.data.address[i].id)
            }
        }
        postOrderComputed(this.data.orderKey, {
            useIntegral: this.data.useIntegral ? 1 : 0,
            couponId: this.data.couponId,
            shipping_type: parseInt(shippingType) + 1,
            payType: this.data.payType,
            orderAddress: dataText.join(',') || '',
        }).then(res => {
            let result = res.data.result;
            if (result) {
                this.setData({
                    totalPrice: result.pay_price,
                    integral_price: result.deduction_price,
                    coupon_price: result.coupon_price,
                    integral: this.data.useIntegral ? result.SurplusIntegral : this.data.userInfo.integral,
                    'priceGroup.storePostage': shippingType == 1 ? 0 : result.pay_postage,
                }, () => this._calculateTotalAmount());
            }
        })
    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        this.setData({
            isClose: true
        });
    },
    ChangCouponsClone: function() {
        this.setData({
            'coupon.coupon': false
        });
    },
    changeTextareaStatus: function() {
        for (var i = 0, len = this.data.coupon.list.length; i < len; i++) {
            this.data.coupon.list[i].use_title = '';
            this.data.coupon.list[i].is_use = 0;
        }
        this.setData({
            textareaStatus: true,
            status: 0,
            "coupon.list": this.data.coupon.list
        });
    },
    /**
     * 处理点击优惠券后的事件
     * 
     */
    ChangCoupons: function(e) {
        var index = e.detail,
            list = this.data.coupon.list,
            couponTitle = '请选择',
            couponId = 0;
        for (var i = 0, len = list.length; i < len; i++) {
            if (i != index) {
                list[i].use_title = '';
                list[i].is_use = 0;
            }
        }
        if (list[index].is_use) {
            //不使用优惠券
            list[index].use_title = '';
            list[index].is_use = 0;
        } else {
            //使用优惠券
            list[index].use_title = '不使用';
            list[index].is_use = 1;
            couponTitle = list[index].coupon_title;
            couponId = list[index].id;
        }
        this.setData({
            couponTitle: couponTitle,
            couponId: couponId,
            'coupon.coupon': false,
            "coupon.list": list,
        });
        this.computedPrice();
    },
    /**
     * 使用积分抵扣
     */
    ChangeIntegral: function() {
        this.setData({
            useIntegral: !this.data.useIntegral
        });
        this.computedPrice();
    },
    /**
     * 选择地址后改变事件
     * @param object e
     */
    OnChangeAddress: function(e) {
        this.computedPrice();
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (!options.cartId) return app.Tips({
            title: '请选择要购买的商品'
        }, {
            tab: 3,
            url: 1
        });
        // if (options.shippingType) this.setData({ shippingType: options.shippingType, storeIndex: options.storeIndex });
        this.setData({
            // showInput: options.showInput,
            couponId: options.couponId || 0,
            pinkId: options.pinkId ? parseInt(options.pinkId) : 0,
            addressId: options.addressId || 0,
            cartId: options.cartId,
            is_address: options.is_address ? true : false,
        });
    },
    dateChange(e) {
        let array = this.data.cartInfo.slice();
        let data = e.detail.value.split("-");
        let _data = data.join("");
        array[e.target.dataset.index].birthday = _data;
        this.setData({
            cartInfo: array
        });
    },
    // event产品的收集信息
    bindHideKeyboard: function(e) {
        if (e.currentTarget.dataset.name === 'mark') {
            this.setData({
                mark: e.detail.value
            });
        } else {
            // 每一个商品的属性修改
            let array = this.data.cartInfo.slice();
            let index = e.currentTarget.dataset.index;
            array[index][e.currentTarget.dataset.name] = e.detail.value;
            this.setData({
                cartInfo: array
            });
        }
    },
    /**
     * 获取当前订单详细信息
     * 
     */
    getConfirm: function() {
        var that = this;
        orderConfirm(this.data.cartId).then(res => {
            let allNum = 0;
            res.data.cartInfo.map((item) => {
                allNum += item.cart_num
                if (item.event_id !== 0) this.setData({
                    showInput: true
                });
            })
            let needAddress = 1
            if (that.data.order_information_limit) {
                needAddress = Math.ceil(allNum / that.data.order_information_limit)
            }
            that.setData({
                caniste_price: res.data.caniste_price,
                needAddress: needAddress,
                allNum: allNum,
                userInfo: res.data.userInfo,
                integral: res.data.userInfo.integral,
                cartInfo: res.data.cartInfo,
                integralRatio: res.data.integralRatio,
                offlinePostage: res.data.offlinePostage,
                orderKey: res.data.orderKey,
                priceGroup: res.data.priceGroup,
                totalPrice: app.help().Add(parseFloat(res.data.priceGroup.totalPrice), parseFloat(res.data.priceGroup.storePostage)),
                seckillId: parseInt(res.data.seckill_id),
                usableCoupon: res.data.usableCoupon,
                // system_store: res.data.system_store,
                store_self_mention: res.data.store_self_mention,
                // real_name:res.data.userInfo.real_name||"",
                // birthday:res.data.userInfo.birthday||"",
                // qq:res.data.userInfo.qq||"",
                // wechat:res.data.userInfo.wechat||"",
                // sign:res.data.userInfo.sign||"",
                maxPackNum: res.data.caniste_num,
                packNum: res.data.caniste_num || 0,
                poster_price: (res.data.caniste_num || 0) * res.data.caniste_price,
            }, () => this._calculateTotalAmount());
            that.data.cartArr[1].title = '可用余额:' + res.data.userInfo.now_money;
            if (res.data.offline_pay_status == 2) that.data.cartArr.pop();
            that.setData({
                cartArr: that.data.cartArr,
                ChangePrice: that.data.totalPrice
            });
            that.getBargainId();
            that.getCouponList();
        }).catch(err => {
            return app.Tips({
                title: err
            }, {
                tab: 3,
                url: 1
            });
        });
    },
    /*
     * 提取砍价和拼团id
     */
    getBargainId: function() {
        var that = this;
        var cartINfo = that.data.cartInfo;
        var BargainId = 0;
        var combinationId = 0;
        cartINfo.forEach(function(value, index, cartINfo) {
            BargainId = cartINfo[index].bargain_id,
                combinationId = cartINfo[index].combination_id
        })
        that.setData({
            BargainId: parseInt(BargainId),
            combinationId: parseInt(combinationId)
        });
        if (that.data.cartArr.length == 3 && (BargainId || combinationId || that.data.seckillId)) {
            that.data.cartArr.pop();
            that.setData({
                cartArr: that.data.cartArr
            });
        }
    },
    /**
     * 获取当前金额可用优惠券
     * 
     */
    getCouponList: function() {
        var that = this;
        let data = {
            cartId: this.data.cartId
        }
        getCouponsOrderPrice(this.data.totalPrice, data).then(res => {
            that.setData({
                'coupon.list': res.data,
                openType: 1
            });
        });
    },

    payItem: function(e) {
        var that = this;
        var active = e.currentTarget.dataset.index;
        that.setData({
            active: active,
            animated: true,
            payType: that.data.cartArr[active].value,
        });
        that.computedPrice();
        setTimeout(function() {
            that.car();
        }, 500);
    },
    coupon: function() {
        this.setData({
            'coupon.coupon': true
        })
    },
    car: function() {
        var that = this;
        that.setData({
            animated: false
        });
    },
    onAddress: function() {
        this.setData({
            textareaStatus: false,
            'address.address': true,
            pagesUrl: '/pages/user_address_list/index?cartId=' + this.data.cartId + '&pinkId=' + this.data.pinkId + '&couponId=' + this.data.couponId
        });
    },
    realName: function(e) {
        this.setData({
            contacts: e.detail.value
        })
    },
    phone: function(e) {
        this.setData({
            contactsTel: e.detail.value
        })
    },
    SubOrder: function(e) {
        var that = this,
            data = {};
        if (!this.data.policy.isAgree) {
            return app.Tips({
                title: '请先阅读并同意协议'
            });
        }
        if (!this.data.payType) return app.Tips({
            title: '请选择支付方式'
        });
        if (this.data.address.length == 0 && !this.data.shippingType) return app.Tips({
            title: '请选择收货地址'
        });
        if (this.data.address.length != this.data.needAddress) return app.Tips({
            title: '选择身份信息数量错误'
        });
        if (this.data.shippingType == 1) {
            if (this.data.contacts == "" || this.data.contactsTel == "")
                return app.Tips({
                    title: '请填写联系人或联系人电话'
                });
            if (!/^1(3|4|5|7|8|9|6)\d{9}$/.test(this.data.contactsTel)) {
                return app.Tips({
                    title: '请填写正确的手机号'
                });
            }
            if (!/^[\u4e00-\u9fa5\w]{2,16}$/.test(this.data.contacts)) {
                return app.Tips({
                    title: '请填写您的真实姓名'
                });
            }
        }
        data = {
            phone: that.data.contactsTel,
            addressId: that.data.address,
            orderAddress: that.data.address,
            formId: '',
            couponId: that.data.couponId,
            payType: that.data.payType,
            useIntegral: that.data.useIntegral,
            bargainId: that.data.BargainId,
            combinationId: that.data.combinationId,
            pinkId: that.data.pinkId,
            seckill_id: that.data.seckillId,
            mark: that.data.mark,
            store_id: that.data.system_store ? that.data.system_store.id : 0,
            'from': 'routine',
            shipping_type: app.help().Add(that.data.shippingType, 1)
        };
        if (that.data.showInput) {
            let array = []
            that.data.cartInfo.forEach(element => {
                if (element.event_id !== 0) {
                    array.push({
                        id: element.id,
                        to_content: element.to_content,
                        wechat_number: element.wechat_number,
                        qq_number: element.qq_number,
                        to_name: element.to_name,
                        birthday: element.birthday,
                    })
                }
            })
            data['to_info'] = JSON.stringify(array)
        }

        if (that.data.maxPackNum > 0) { //海报筒数量
            data.canister_num = that.data.packNum
        }

        if (data.payType == 'yue' && parseFloat(that.data.userInfo.now_money) < parseFloat(that.data.totalPrice)) return app.Tips({
            title: '余额不足！'
        });
        wx.showLoading({
            title: '订单支付中'
        });
        openPaySubscribe().then(() => {
            orderCreate(this.data.orderKey, data).then(res => {
                var status = res.data.status,
                    orderId = res.data.result.orderId,
                    jsConfig = res.data.result.jsConfig,
                    goPages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=' + res.msg;
                switch (status) {
                    case 'ORDER_EXIST':
                    case 'EXTEND_ORDER':
                    case 'PAY_ERROR':
                        wx.hideLoading();
                        return app.Tips({
                            title: res.msg
                        }, {
                            tab: 5,
                            url: goPages
                        });
                        break;
                    case 'SUCCESS':
                        wx.hideLoading();
                        if (that.data.BargainId || that.data.combinationId || that.data.pinkId || that.data.seckillId)
                            return app.Tips({
                                title: res.msg,
                                icon: 'success'
                            }, {
                                tab: 4,
                                url: goPages
                            });
                        return app.Tips({
                            title: res.msg,
                            icon: 'success'
                        }, {
                            tab: 5,
                            url: goPages
                        });
                        break;
                    case 'WECHAT_PAY':
                        that.setData({
                            toPay: true
                        });
                        wx.requestPayment({
                            timeStamp: jsConfig.timestamp,
                            nonceStr: jsConfig.nonceStr,
                            package: jsConfig.package,
                            signType: jsConfig.signType,
                            paySign: jsConfig.paySign,
                            success: function(res) {
                                wx.hideLoading();
                                if (that.data.BargainId || that.data.combinationId || that.data.pinkId || that.data.seckillId)
                                    return app.Tips({
                                        title: '支付成功',
                                        icon: 'success'
                                    }, {
                                        tab: 4,
                                        url: goPages
                                    });
                                return app.Tips({
                                    title: '支付成功',
                                    icon: 'success'
                                }, {
                                    tab: 5,
                                    url: goPages
                                });
                            },
                            fail: function(e) {
                                wx.hideLoading();
                                return app.Tips({
                                    title: '取消支付'
                                }, {
                                    tab: 5,
                                    url: goPages + '&status=2'
                                });
                            },
                            complete: function(e) {
                                wx.hideLoading();
                                //关闭当前页面跳转至订单状态
                                if (res.errMsg == 'requestPayment:cancel') return app.Tips({
                                    title: '取消支付'
                                }, {
                                    tab: 5,
                                    url: goPages + '&status=2'
                                });
                            },
                        })
                        break;
                    case 'PAY_DEFICIENCY':
                        wx.hideLoading();
                        //余额不足
                        return app.Tips({
                            title: res.msg
                        }, {
                            tab: 5,
                            url: goPages + '&status=1'
                        });
                        break;
                }
            }).catch(err => {
                wx.hideLoading();
                return app.Tips({
                    title: err
                });
            });
        });
    },
    _calculateTotalAmount() {
        this.setData({
            totalAmount: parseFloat(this.data.totalPrice + this.data.poster_price).toFixed(2),
        })
    }
})